<?php

namespace app\admin\controller;
use app\admin\validate\UserValidate;
use app\CommonController;
use think\exception\ValidateException;
use app\service\UserService;
use think\facade\Session;

class Login extends CommonController
{
    public function __construct(UserService $service)
    {
        parent::__construct();
        $this->service = $service;

    }

    public function index()
    {

        if (!empty(Session::get("uid"))) {
            return redirect("/index/index");
        }
        if (!$this->request->isPost()) {
            return $this->fetch("index");
        }
        $params = $this->request->post();
        $ip = $this->request->ip();
        try {
            validate(UserValidate::class)->scene("login")->check($params);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        try {
            $this->service->login($params["username"], $params["password"]);
        } catch (ValidateException $e) {
            $this->service->updateUserByUsername($params["username"], false, $ip);
            $this->error($e->getMessage());
        }
        $this->service->updateUserByUsername($params["username"], true, $ip);
        $this->success("登录成功", "/index/index");
    }


    public function out()
    {
        $this->app->session->destroy();
        $this->success('退出登录成功!', "/login/index");
    }
}